using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;

namespace 第十次课堂作业
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Baidu.ReadOnly = true;//只读
            Bing.ReadOnly = true;
        }
        WebClient webClient = new WebClient();
        string patternHtml = "<[^>]+>"; //去除<>标签
        string patternOthers = "[^\u4e00-\u9fa5\u3400-\u4DBF]+";    //只保留汉字

        public static string myUrlEncoding(string word)//将关键字编码
        {
            byte[] bytes = Encoding.UTF8.GetBytes(word);
            string res = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                res += "%" + bytes[i].ToString("X2");
            }
            return res;
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            string words = searchBox.Text;

            string urlBaidu = "https://www.baidu.com/s?wd=" + myUrlEncoding(words);//百度
            string str1 = await AccessTheWebAsync(urlBaidu);//异步编程方式下载网页
            str1 = Regex.Replace(str1, patternHtml, "");
            str1 = Regex.Replace(str1, patternOthers, "");
            if (str1.Length > 200)
            {
                Baidu.Text = str1.Substring(0, 200) + urlBaidu;
            }
            else
            {
                Baidu.Text = str1 + urlBaidu;
            }

            string urlBing = "https://cn.bing.com/search?q=" + myUrlEncoding(words); //必应
            urlBing += "&rnd=" + new Random().Next();
            string str2 = await AccessTheWebAsync(urlBing); //异步编程方式下载网页
            str2 = Regex.Replace(str2, patternHtml, "");
            str2 = Regex.Replace(str2, patternOthers, "");
            if (str2.Length > 200)
            {
                Bing.Text = str2.Substring(0, 200) + urlBing;
            }
            else
            {
                Bing.Text = str2 + urlBing;
            }
        }
        async Task<string> AccessTheWebAsync(string url)//异步编程方式下载网页
        {
            HttpClient client = new HttpClient();
            Task<string> getStringTask = client.GetStringAsync(url);
            string urlContents = await getStringTask;
            return urlContents;
        }
    }
    
}